package com.ooqiu.gaming.ui.article_detail;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.webkit.JavascriptInterface;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ooqiu.gaming.GamingApp;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.common.Constants;
import com.ooqiu.gaming.common.entities.GamingUser;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.ui.web.X5WebView;
import com.ooqiu.gaming.utils.LocalBroadcastManagerUtil;
import com.ooqiu.gaming.utils.LogUtil;
import com.ooqiu.gaming.utils.PayResult;
import com.ooqiu.gaming.view.ToastUtil;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.Map;

import es.dmoral.toasty.Toasty;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * @author Eenie
 * @date 2017/11/29
 */

public class AndroidBridge implements UMShareListener {

    private Activity mActivity;
    private RxPermissions mRxPermissions;
    ShareAction mShareAction;
    QMUITipDialog mTipDialog;
    GamingApi mGamingApi;
    UserStorage mUserStorage;
    X5WebView mX5WebView;

    public AndroidBridge(Activity activity) {
        mActivity = activity;
        mRxPermissions = new RxPermissions(activity);
        mShareAction = new ShareAction(mActivity);
        mGamingApi = ((GamingApp) mActivity.getApplication()).getApplicationComponent().getGamingApi();
        mUserStorage = ((GamingApp) mActivity.getApplication()).getApplicationComponent().getUserStorage();

        mTipDialog = new QMUITipDialog.Builder(mActivity)
                .setTipWord("正在分享...")
                .create();
        mTipDialog.setCancelable(true);

    }

    public AndroidBridge(Activity activity, X5WebView x5WebView) {

        mActivity = activity;
        mRxPermissions = new RxPermissions(activity);
        mShareAction = new ShareAction(mActivity);
        mGamingApi = ((GamingApp) mActivity.getApplication()).getApplicationComponent().getGamingApi();
        mUserStorage = ((GamingApp) mActivity.getApplication()).getApplicationComponent().getUserStorage();

        mTipDialog = new QMUITipDialog.Builder(mActivity)
                .setTipWord("正在分享...")
                .create();
        mTipDialog.setCancelable(true);
        mX5WebView = x5WebView;
    }


    @JavascriptInterface
    public void showToast(String msg) {
        Toasty.success(mActivity, msg).show();

    }

    @JavascriptInterface
    public void alert(String msg) {
        new AlertDialog.Builder(mActivity).setMessage(msg)
                .setTitle("提示：")
                .setPositiveButton("确定", null)
                .create()
                .show();
    }

    @JavascriptInterface
    public void alert(String msg, String config) {


        new AlertDialog.Builder(mActivity).setMessage(msg)
                .setTitle("提示：")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    @JavascriptInterface
    public String getToken() {
        return mUserStorage.getToken();
    }


    @JavascriptInterface
    public int share(String content) {

        LogUtil.json(content);
        JSONObject shareInfo = JSON.parseObject(content);
        final SHARE_MEDIA p;

        if (shareInfo.getIntValue("type") == 1) {
            p = SHARE_MEDIA.QQ;
        } else if (shareInfo.getIntValue("type") == 3) {
            p = SHARE_MEDIA.SINA;
        } else {
            p = SHARE_MEDIA.WEIXIN;
        }

        final UMWeb umWeb = new UMWeb(shareInfo.getString("url"));
        umWeb.setTitle(shareInfo.getString("title"));
        umWeb.setThumb(new UMImage(mActivity, shareInfo.getString("shareImg")));
        umWeb.setDescription(Html.fromHtml(shareInfo.getString("description")).toString());
        mRxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new DefaultObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            mShareAction.setPlatform(p)//传入平台
                                    .withMedia(umWeb)
                                    .setCallback(AndroidBridge.this)
                                    .share();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });


        return 0;
    }

    @JavascriptInterface
    public void recommendItemClick(int content_type, int news_id) {
        if (content_type == 3) {
            ARouter.getInstance().build(VideoDetailActivity.PATH)
                    .withInt("news_id", news_id)
                    .navigation();

        } else {
            ARouter.getInstance().build(ArticleDetailActivity.PATH)
                    .withInt("news_id", news_id)
                    .navigation();
        }
        mActivity.finish();
    }

    @JavascriptInterface
    public void H5Login(final String userInfo) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LogUtil.e("H5Login = " + userInfo);
                GamingUser user = JSON.parseObject(userInfo, GamingUser.class);
                ((GamingApp) mActivity.getApplication()).getApplicationComponent().getUserStorage().saveUser(user);
            }
        });
    }

    @JavascriptInterface
    public void finish() {
        mActivity.finish();
    }

    @JavascriptInterface
    public void collect(int type, int newsId, boolean collect) {
        mGamingApi.collect(type, newsId, collect)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<String>(mActivity) {
                    @Override
                    public void onNext(String s) {

                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    @JavascriptInterface
    public String platform() {
        return "android";
    }

    @JavascriptInterface
    public void aliPay(final String orderInfo, final String errorUrl, final String successUrl) {

        LogUtil.e("%s\n%s\n%s", orderInfo, errorUrl, successUrl);

        mGamingApi.aliPay(mActivity, orderInfo)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<Map<String, String>>(mActivity) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(Map<String, String> stringStringMap) {
                        //PayResult非常简单的工具类,把map里的结果取出来(来自支付宝demo)
                        PayResult payResult = new PayResult(stringStringMap);
                        Bundle bundle = new Bundle();



                        bundle.getString("error_url", "1445454");
                        bundle.getString("success_url", successUrl);




                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();//状态码
                        String memo = payResult.getMemo();//附加信息,如果不为空可以提示该内容
                        switch (resultStatus) {
                            case "9000":
                                bundle.putBoolean("pay_res", true);

                                LocalBroadcastManagerUtil.post(mActivity, Constants.ACTION_PAY_STATE_CHANGE, bundle);
                                ToastUtil.showSuccess("支付成功");
                                break;
                            case "8000":
                                //支付结果确认中
                                break;
                            case "4000":
                                bundle.putBoolean("pay_res", true);
                                LocalBroadcastManagerUtil.post(mActivity, Constants.ACTION_PAY_STATE_CHANGE, bundle);
                                ToastUtil.showSuccess("支付失败");
                                break;
                            case "5000":
                                //重复请求
                                break;
                            case "6001":
                                //用户中途取消
                                break;
                            case "6002":
                                //网络连接出错
                                break;
                            case "6004":
                                //支付结果未知,请查询订单
                                break;
                            default:
                                //其它支付错误
                                break;
                        }
                        ToastUtil.showSuccess(memo);
                    }

                    @Override
                    public void onFinish() {

                    }
                });


    }

    @JavascriptInterface
    public void wxPay(String orderInfo, String errorUrl, String successUrl) {
        LogUtil.e("%s\n%s\n%s", orderInfo, errorUrl, successUrl);
        mGamingApi.wxPay(mActivity, orderInfo);
    }


    @Override
    public void onStart(SHARE_MEDIA share_media) {
        mTipDialog.show();
    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {
        mTipDialog.dismiss();
    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        mTipDialog.dismiss();
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
        mTipDialog.dismiss();
    }
}
